package com.example.terminalservice.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 28142
 * @description 发送邮件工具类
 * @date 2023/8/5 9:01
 */
@Component
public class EmailUtils {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${spring.mail.username}")
    private String mailFrom;
    public String sendEmail(String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(email);
        message.setSubject("邮箱登录验证");
        // 使用hutool生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 20);
        lineCaptcha.write(System.getProperty("user.dir") + "\\code.png");
        String code = lineCaptcha.getCode();
        message.setText("您的验证码是" + code + "，在5分钟内有效。如非本人操作请忽略本消息。");
        javaMailSender.send(message);
        // 将验证码存入redis中，key为邮箱
        stringRedisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(email + code, "time", 1, TimeUnit.MINUTES);
        return code;
    }
}
